package com.dealin.writer.bean;

import android.os.Environment;
import android.util.Log;

import com.dealin.dealinlibs.tool.EncryptTool;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by lenovo on 2016/6/20.
 */
public class Project {
    public static String PROJECT_ROOT_PATH= Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.dealin.writer/novel/";
    public static String PROJECT_OUTPUT_PATH="sdcard/唯美小说/";
    private String name="未命名",author="",createDate=new Date().toLocaleString(),refreshDate=new Date().toLocaleString(),summary="暂无摘要",password="";
    private int groupCount=0;
    public ArrayList<Group> groups=new ArrayList<Group>();
    private Outline outline;
    private String novelPath;
    public Project()
    {

    }
    public Project(File file) throws Exception {
        init(file.getAbsolutePath());
    }
    public Project(String name)throws Exception
    {
        this.name=name;
        init();
    }

    public Project createNewNovel(String name,String author)throws Exception
    {
        if(new File(PROJECT_ROOT_PATH+name+".novx").exists()){
            novelPath=PROJECT_ROOT_PATH+name+Math.ceil(Math.random()*10)+".novx";
        }else{
            novelPath=PROJECT_ROOT_PATH+name+".novx";
        }
        this.name=name;
        this.author=author;
        save();
        return this;
    }
    /*
    **group相关操作
     */
    public void createNewGroup(String name)
    {
        Group group=new Group();
        group.setName(name);
        group.setCreateDate(new Date().toLocaleString());
        group.setRefreshDate(group.getCreateDate());
        group.setSummary("暂无摘要");
        group.setPassword("");
        group.setId(groupCount);
        groupCount+=1;
        groups.add(group);
    }

    public void outputNovel() throws Exception{
        StringBuffer stringBuffer=new StringBuffer("《"+getName()+"》");
        stringBuffer.append("\n作者："+getAuthor());
        stringBuffer.append("\n字数："+getCount());
        stringBuffer.append("\n创建日期："+getCreateDate());
        stringBuffer.append("\n更新日期："+getRefreshDate());
        stringBuffer.append("\n本小说由【唯美写作】创建");
        stringBuffer.append("\n");
        for (int i=0;i<groupCount;i++) {
            stringBuffer.append("\n\n"+getGroup(i).getName());
            stringBuffer.append("\n本卷字数："+getGroup(i).getCount());
            stringBuffer.append("\n创建日期："+getGroup(i).getCreateDate());
            stringBuffer.append("\n更新日期："+getGroup(i).getRefreshDate());
            for (int j=0;j<getGroup(i).getChapterCount();j++) {
                stringBuffer.append("\n"+getGroup(i).getName()+"  "+getGroup(i).getChapter(j).getName());
                stringBuffer.append("\n本章字数："+getGroup(i).getChapter(j).getCount());
                stringBuffer.append("\n创建日期："+getGroup(i).getChapter(j).getCreateDate());
                stringBuffer.append("\n更新日期："+getGroup(i).getChapter(j).getRefreshDate());
                stringBuffer.append("\n"+getGroup(i).getChapter(j).getContent());
            }
        }
        File f=new File(PROJECT_OUTPUT_PATH+getName()+".txt");
        if(!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        FileOutputStream fos=new FileOutputStream(f);
        byte[] bytes= stringBuffer.toString().getBytes();
        fos.write(bytes);
        fos.close();

    }

    public void outputGroup(int i) throws Exception{
        StringBuffer stringBuffer=new StringBuffer("《"+getName()+"》");
        stringBuffer.append("\n作者："+getAuthor());
        stringBuffer.append("\n字数："+getCount());
        stringBuffer.append("\n创建日期："+getCreateDate());
        stringBuffer.append("\n更新日期："+getRefreshDate());
        stringBuffer.append("\n本小说由【唯美写作】创建");
        stringBuffer.append("\n");
        stringBuffer.append("\n\n"+getGroup(i).getName());
        stringBuffer.append("\n本卷字数："+getGroup(i).getCount());
        stringBuffer.append("\n创建日期："+getGroup(i).getCreateDate());
        stringBuffer.append("\n更新日期："+getGroup(i).getRefreshDate());
        for (int j=0;j<getGroup(i).getChapterCount();j++) {
            stringBuffer.append("\n" + getGroup(i).getName() + "  " + getGroup(i).getChapter(j).getName());
            stringBuffer.append("\n本章字数：" + getGroup(i).getChapter(j).getCount());
            stringBuffer.append("\n创建日期：" + getGroup(i).getChapter(j).getCreateDate());
            stringBuffer.append("\n更新日期：" + getGroup(i).getChapter(j).getRefreshDate());
            stringBuffer.append("\n"+getGroup(i).getChapter(j).getContent());
        }
        saveFile(stringBuffer.toString(),PROJECT_OUTPUT_PATH+getName()+"/"+getGroup(i).getName()+".txt");
    }
    public void outputChapter(int i,int j) throws Exception{
        StringBuffer stringBuffer=new StringBuffer("《"+getName()+"》");
        stringBuffer.append("\n作者："+getAuthor());
        stringBuffer.append("\n" + getGroup(i).getName() + "  " + getGroup(i).getChapter(j).getName());
        stringBuffer.append("\n本章字数：" + getGroup(i).getChapter(j).getCount());
        stringBuffer.append("\n创建日期：" + getGroup(i).getChapter(j).getCreateDate());
        stringBuffer.append("\n更新日期：" + getGroup(i).getChapter(j).getRefreshDate());
        stringBuffer.append("\n"+getGroup(i).getChapter(j).getContent());
        saveFile(stringBuffer.toString(),PROJECT_OUTPUT_PATH+getName()+"/"+getGroup(i).getName()+".txt");
    }
    /*
    **chapter相关操作
     */
    public String getChapterName(int groupIndex,int chapterIndex)
    {
        return getGroup(groupIndex).getChapter(chapterIndex).getName();
    }
    public String getChapterContent(int groupIndex,int chapterIndex)
    {
        return getGroup(groupIndex).getChapter(chapterIndex).getContent();
    }
    public String getChapterSummary(int groupIndex,int chapterIndex)
    {
        return getGroup(groupIndex).getChapter(chapterIndex).getSummary();
    }
    public void setChapterName(int groupIndex,int chapterIndex,String value)
    {
        getGroup(groupIndex).getChapter(chapterIndex).setName(value);
    }
    public void setChapterContent(int groupIndex,int chapterIndex,String value)
    {
        getGroup(groupIndex).getChapter(chapterIndex).setContent(value);
        getGroup(groupIndex).setRefreshDate(new Date().toLocaleString());
        setRefreshDate(new Date().toLocaleString());
    }
    public void setChapterSummary(int groupIndex,int chapterIndex,String value)
    {
        getGroup(groupIndex).getChapter(chapterIndex).setSummary(value);
    }
    public boolean deleteChapter(int groupIndex,int chapterIndex)
    {
        return getGroup(groupIndex).deleteChapter(chapterIndex);
    }
    public int getCount()
    {
        int c=0;
        for(int i=0;i<groupCount;i++)
        {
            c+=groups.get(i).getCount();
        }
        return c;
    }

    public void createNewChapter(int groupIndex,String chapterName)
    {
        groups.get(groupIndex).createNewChapter(chapterName);
    }

    /*
    **项目操作
     */
    public boolean delete()
    {
        return new File(novelPath).delete();
    }
    public void save() throws Exception
    {
        saveFile(toJSONObject(),novelPath);
    }
    //转换为JSONObject
    public String toJSONObject() throws Exception
    {
        Gson g=new Gson();
        return g.toJson(this);
    }
    /*
    **以下是get方法
     */
    public Group getGroup(int index)
    {
        if(index>=0&&index<groups.size())
        {
            return groups.get(index);
        }else{
            return null;
        }
    }
    public String getName()
    {
        return name;
    }
    public String getAuthor()
    {
        return author;
    }
    public String getCreateDate()
    {
        return createDate;
    }
    public String getRefreshDate()
    {
        return refreshDate;
    }
    public String getSummary()
    {
        return summary;
    }
    public String getPassword()
    {
        return password;
    }
    public int getGroupCount()
    {
        return groupCount;
    }
    public Outline getOutline()
    {
        return outline;
    }
    public String getNovelPath() {
        return novelPath;
    }

    public String getProjectDetail() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("小说名称："+getName());
        stringBuilder.append("\n小说作者："+getAuthor());
        stringBuilder.append("\n总字数　："+getCount());
        stringBuilder.append("\n创建日期："+getCreateDate());
        stringBuilder.append("\n更新日期："+getRefreshDate());
        stringBuilder.append("\n分卷数目："+getGroupCount());
        stringBuilder.append("\n小说地址："+getNovelPath());
        return stringBuilder.toString();
    }
    /*
    **以下是set方法
     */
    public void setName(String s)throws Exception
    {
        File file=new File(PROJECT_ROOT_PATH+name+".novx");
        file.delete();
        name=s;
        save();
    }
    public void setAuthor(String s)throws Exception
    {
        author=s;
        save();
    }
    public void setCreateDate(String s)throws Exception
    {
        createDate=s;
        save();
    }
    public void setRefreshDate(String s)
    {
        refreshDate=s;
    }
    public void setSummary(String s)throws Exception
    {
        summary=s;
        save();
    }
    public void setPassword(String s)throws Exception
    {
        password=s;
        save();
    }
    public void setOutline(Outline newone)throws Exception
    {
        outline=newone;
        save();
    }
    public void init() throws Exception
    {
        String s=Project.PROJECT_ROOT_PATH+name+".novx";
        novelPath=PROJECT_ROOT_PATH+name+".novx";
        JSONObject project=new JSONObject(readFile(s));
        //Log.e("readFile",readFile(file.getAbsolutePath()));
        name=project.getString("name");
        author=project.getString("author");
        createDate=project.getString("createDate");
        refreshDate=project.getString("refreshDate");
        password=project.getString("password");
        summary=project.getString("summary");
        JSONArray ja=project.getJSONArray("groups");
        for(int i=0;i<ja.length();i++)
        {
            groups.add(new Group(ja.getJSONObject(i)));
        }
    }
    public void init(String path) throws Exception
    {
        JSONObject project=new JSONObject(readFile(path));
        novelPath=path;
        Log.e("readFile",readFile(path));
        name=project.getString("name");
        author=project.getString("author");
        createDate=project.getString("createDate");
        refreshDate=project.getString("refreshDate");
        password=project.getString("password");
        summary=project.getString("summary");
        groupCount=project.getInt("groupCount");
        JSONArray ja=project.getJSONArray("groups");
        for(int i=0;i<ja.length();i++)
        {
            groups.add(new Group(ja.getJSONObject(i)));
        }
    }

    public void deleteGroup(int groupId) {
        if(groupId>=0&&groupId<groups.size())
        groups.remove(groupId);
        groupCount=groups.size();
    }
    /*
    **辅助
     */
    public static String readFile(String path) throws Exception
    {
        File file=new File(path);
        FileInputStream fis=new FileInputStream(file);
        byte[] bytes=new byte[fis.available()];
        fis.read(bytes);
        return  EncryptTool.decryptByChar(new String(bytes));
    }

    public static void saveFile(String content, String novelPath)throws Exception {
        File f=new File(novelPath);
        if(!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        FileOutputStream fos=new FileOutputStream(f);
        byte[] bytes= EncryptTool.encryptByChar(content).getBytes();
        fos.write(bytes);
        fos.close();
    }
}


